<?php

namespace app\admin\command;


use think\console\Command;
use think\console\Input;
use think\console\input\Option;
use think\console\Output;
use think\Db;
use app\common\library\ImageCraw;
use \Exception;
use AlibabaCloud\Tea\Utils\Utils;
use Darabonba\OpenApi\Models\Config;
use AlibabaCloud\Tea\Utils\Utils\RuntimeOptions;
use AlibabaCloud\SDK\Facebody\V20191230\Models\AddFaceEntityRequest; //人脸样本添加
use AlibabaCloud\SDK\Facebody\V20191230\Models\AddFaceAdvanceRequest; //人脸数据添加
use AlibabaCloud\SDK\Facebody\V20191230\Models\SearchFaceAdvanceRequest;//人脸搜索
use AlibabaCloud\SDK\Facebody\V20191230\Models\DeleteFaceEntityRequest; //人脸样本删除
use AlibabaCloud\SDK\Facebody\V20191230\Facebody;
use GuzzleHttp\Psr7\Stream;


class FaceSearch extends Command
{
    protected $number;
    protected function configure()
    {
        $this
            ->setName('faceSearch')
            ->setDescription('faceSearch');
    }

    protected function execute(Input $input, Output $output)
    {
        $photo =Db::name('BroadcastImageAvatar')->where('status',0)->limit(200)->select();
        if(!empty($photo)){
            $this->number = 1;
            foreach ($photo as $key => $value) {
                $this->faceload($value);
                sleep(1);
            }
        }
    }
    protected function faceload($photo){
        $path = ROOT_PATH.'public';
        $image = $path.$photo['avatar'];
        $searchRlt = $this->SearchFaceAdvance($image);
        if($searchRlt['code'] == '200'){
            if($searchRlt["Data"]['MatchList'][0]['QualitieScore']>90){
                dump($photo['id']);
                dump($searchRlt["Data"]['MatchList'][0]['FaceItems'][0]['Confidence']);
                dump($searchRlt["Data"]['MatchList'][0]['FaceItems'][0]['EntityId']);
                if(isset($searchRlt["Data"]['MatchList'][0]['FaceItems'][0]['Confidence']) &&  $searchRlt["Data"]['MatchList'][0]['FaceItems'][0]['Confidence'] > 70 ){
                    $avatar_id = $searchRlt["Data"]['MatchList'][0]['FaceItems'][0]['EntityId'];
                    Db::name('BroadcastImageAvatar')->where('id',$photo['id'])->update(['avatar_id'=>$avatar_id,'status'=>1]);
                }else{
                    $number = $this->number;
                    if($number%2 == 1){
                        $entityId = 'P'.$photo['id'];
                        $this->addFaceEntity($entityId);
                        $this->AddFaceAdvance($image,$entityId);
                    }
                    $this->number = $number+1;
                }
            }else{
                Db::name('BroadcastImageAvatar')->where('id',$photo['id'])->delete();
            }
        }else{
            Db::name('BroadcastImageAvatar')->where('id',$photo['id'])->delete();
        }
        
    }
    protected function SearchFaceAdvance($image){
        $config = get_addon_config('alioss');
        $aliConfig = new Config([
            // 必填，您的 AccessKey ID
            "accessKeyId" => $config['accessKeyId'],
            // 必填，您的 AccessKey Secret
            "accessKeySecret" => $config['accessKeySecret']
        ]);
        // 访问的域名
        $aliConfig->endpoint = "facebody.cn-shanghai.aliyuncs.com";
        $faceBody = new Facebody($aliConfig);
        $file = fopen($image, 'rb');
        // 场景二，使用任意可访问的url
        // $file = fopen('https://viapi-test-bj.oss-cn-beijing.aliyuncs.com/viapi-3.0domepic/facebody/AddFace/AddFace.png', 'rb');
        $stream = new Stream($file);
        $searchFaceAdvanceRequest = new SearchFaceAdvanceRequest([
            "dbName" => "default",
            "imageUrlObject" => $stream,
            "limit" => 1,
            'MaxFaceNum'=>1,
        ]);
        $runtime = new RuntimeOptions([]);
        try {
            $resp = $faceBody->searchFaceAdvance($searchFaceAdvanceRequest, $runtime);
            $respon =json_decode(
                Utils::toJSONString($resp->body),true
            );
            $respon['code']='200';
            return $respon;
        } catch (\Exception $exception) {
            # 获取整体报错信息
            echo Utils::toJSONString($exception);
            # 获取单个字段
            $respon['code']='500';
            return $respon;
        }
    }
    protected function addFaceEntity($entityId){
        $config = get_addon_config('alioss');
        $aliConfig = new Config([
            // 必填，您的 AccessKey ID
            "accessKeyId" => $config['accessKeyId'],
            // 必填，您的 AccessKey Secret
            "accessKeySecret" => $config['accessKeySecret']
        ]);
        // 访问的域名
        $aliConfig->endpoint = "facebody.cn-shanghai.aliyuncs.com";
        $faceBody = new Facebody($aliConfig);
        $addFaceEntityRequest = new AddFaceEntityRequest([
            "dbName" => "default",
            "entityId" => $entityId,
        ]);
        $runtime = new RuntimeOptions([]);
        try {
            $resp = $faceBody->addFaceEntityWithOptions($addFaceEntityRequest, $runtime);
            $respon['code']='200';
            return $respon;
        } catch (\Exception $exception) {
            # 获取整体报错信息
            echo Utils::toJSONString($exception);
            # 获取单个字段
            $respon['code']='500';
            return $respon;
        }
    }
    protected function deleteFaceEntity($entityId){
        $config = get_addon_config('alioss');
        $aliConfig = new Config([
            // 必填，您的 AccessKey ID
            "accessKeyId" => $config['accessKeyId'],
            // 必填，您的 AccessKey Secret
            "accessKeySecret" => $config['accessKeySecret']
        ]);
        // 访问的域名
        $aliConfig->endpoint = "facebody.cn-shanghai.aliyuncs.com";
        $faceBody = new Facebody($aliConfig);
        $deleteFaceEntityRequest = new DeleteFaceEntityRequest([
            "dbName" => "default",
            "entityId" => $entityId,
        ]);
        $runtime = new RuntimeOptions([]);
        try {
            $resp = $faceBody->deleteFaceEntityWithOptions($deleteFaceEntityRequest, $runtime);
            $respon['code']='200';
            return $respon;
        } catch (\Exception $exception) {
            # 获取整体报错信息
            echo Utils::toJSONString($exception);
            # 获取单个字段
            $respon['code']='500';
            return $respon;
        }
    }
    protected function AddFaceAdvance($image,$entityId){
        $config = get_addon_config('alioss');
        $aliConfig = new Config([
            // 必填，您的 AccessKey ID
            "accessKeyId" => $config['accessKeyId'],
            // 必填，您的 AccessKey Secret
            "accessKeySecret" => $config['accessKeySecret']
        ]);
        // 访问的域名
        $aliConfig->endpoint = "facebody.cn-shanghai.aliyuncs.com";
        $faceBody = new Facebody($aliConfig);
        $file = fopen($image, 'rb');
        // 场景二，使用任意可访问的url
        // $file = fopen('https://viapi-test-bj.oss-cn-beijing.aliyuncs.com/viapi-3.0domepic/facebody/AddFace/AddFace.png', 'rb');
        $stream = new Stream($file);
        $addFaceAdvanceRequest = new AddFaceAdvanceRequest([
            "dbName" => "default",
            "imageUrlObject" => $stream,
            "entityId" => $entityId,
        ]);
        $runtime = new RuntimeOptions([]);
        try {
            $resp = $faceBody->addFaceAdvance($addFaceAdvanceRequest, $runtime);
            $respon =json_decode(
                Utils::toJSONString($resp->body),true
            );
            $respon['code']='200';
            return $respon;
        } catch (\Exception $exception) {
            # 获取整体报错信息
            echo Utils::toJSONString($exception);
            # 获取单个字段
            $respon['code']='500';
            return $respon;
        }
    }
}